// package-activity/pages/store-activity-edit-spokes/index.js
const app = getApp();
import { PACKAGE_STORE_PAGE, PACKAGE_ACTIVITY_PAGE } from '../../../constants/route';
import { ManageTargetInfoUpdateMixins } from '../../../behaviors/page';
import { navTo, navToAction, navBack, tipToast } from '../../../common/env';
import { ACTIVITY_STATUS_VALUE, ACTIVITY_BONUS_RATE } from '../../../constants/activity';
import { arr2Obj, formatInputDecimal } from '../../../common/utils';
import { TipDialog } from '../../../common/tip';
import { getEndorsement } from '../../../api/sto';
import { getStoreProductListByIds } from '../../../api/product';

Page({
    mixins: [ManageTargetInfoUpdateMixins],
    data: {
        ACTIVITY_BONUS_RATE,
        activityInfo: {},
        activityProductWithSkusMap: {},
        productPercentOffMap: {},
        modifyFlag: true,
        allCommissionModal: {
            show: false,
        },
    },
    onLoad(options) {
        app.event.addListener('sendActivityInfo', this._handleSendActivity.bind(this));
    },
    onUnload() {
        app.event.removeListener('sendActivityInfo');
    },
    onShow() {
        app.event.addListener('getActivityInfo', this._handleSendActivity.bind(this));
        this._handleGetSpokesInfo();
    },
    _handleSendActivity(activityInfo) {
        const activityProductWithSkusMap = arr2Obj(activityInfo.activityProductWithSkus, 'productId');
        const consignmentBonusSettingsMap = arr2Obj(activityInfo.consignment.consignmentBonusSettings, 'productId');
        activityInfo.consignment.consignmentBonusSettings = activityInfo.activityProductWithSkus.map(ps => ({
            productId: ps.productId,
            bonusRate: consignmentBonusSettingsMap[ps.productId] ? consignmentBonusSettingsMap[ps.productId].bonusRate : '',
        }));
        const modifyFlag = !activityInfo.processStatus || activityInfo.processStatus === ACTIVITY_STATUS_VALUE.draft;
        this.setData({
            modifyFlag,
            activityInfo,
            activityProductWithSkusMap,
        });
        this._handleGetProductPercentOff(activityInfo);
    },
    async _handleGetProductPercentOff(activityInfo) {
        const productIds = activityInfo.activityProductWithSkus.map(p => p.productId);
        if (productIds.length) {
            const res = getStoreProductListByIds({ productIds })
            this.setData({
                productPercentOffMap: arr2Obj(res, 'productId'),
            });
        }
    },
    async _handleGetSpokesInfo() {
        const { manageTargetInfo } = this.data;
        const endorsementInfo = await getEndorsement();
        if (!endorsementInfo.isOpen && !manageTargetInfo.spokesmanCount) {
            TipDialog({
                title: '温馨提示',
                message: '当前无可帮忙代言人，请开启代言人招募计划，否则将影响活动效果哟',
                confirmButtonText: '前往开启',
                ok() {
                    navTo(PACKAGE_STORE_PAGE['storeSpokesman']);
                },
            });
        }
    },
    handleShoAllCommissionModal() {
        if (!this.data.modifyFlag) {
            tipToast('活动已发布，此项不能编辑');
            return;
        }
        this.setData({
            'allCommissionModal.show': true,
        })
    },
    handleChangeAllCommission(e) {
        const bonusRate = formatInputDecimal(e.detail, 1);
        if (bonusRate < 0) {
            tipToast('请输入正确的分账比例');
            return;
        }
        if (bonusRate > ACTIVITY_BONUS_RATE) {
            tipToast(`分账比例最高不超过${ACTIVITY_BONUS_RATE}%`);
            return;
        }
        let { consignmentBonusSettings } = this.data.activityInfo.consignment;
        consignmentBonusSettings = consignmentBonusSettings.map(c => {
            const maxPercent = productPercentOffMap[c.productId] ? productPercentOffMap[c.productId].percentOff : 0;
            if (bonusRate * 10 <= maxPercent) {
                c.bonusRate = bonusRate * 10;
            }
            return c;
        });
        this.setData({
            'activityInfo.consignment.consignmentBonusSettings': consignmentBonusSettings
        });
    },
    handleChangeProductCommission(e) {
        if (!this.data.modifyFlag) {
            tipToast('活动已发布，此项不能编辑');
            return;
        }
        const { productId, bonusRate } = e.detail;
        const { consignmentBonusSettings } = this.data.activityInfo.consignment;
        const idx = consignmentBonusSettings.findIndex(c => c.productId === productId);
        consignmentBonusSettings[idx].bonusRate = bonusRate;
        this.setData({
            'activityInfo.consignment.consignmentBonusSettings': consignmentBonusSettings,
        });
    },
    handleChangeAllowAllSpokesman(e) {
        if (!this.data.modifyFlag) {
            tipToast('活动已发布，此项不能编辑');
            return;
        }
        const { value } = e.currentTarget.dataset;
        this.setData({
            'activityInfo.consignment.allowAllSpokesman': value,
        });
    },
    handleNavToSpokesman() {
        const { activityInfo } = this.data;
        navToAction(PACKAGE_ACTIVITY_PAGE['storeActivityEditSpokesman'], null, {
            success(res) {
                setTimeout(() => {
                    app.event.trigger('sendActivityInfoSpokes', activityInfo);
                }, 800);
            },
        });
    },
    handleSave() {
        if (!this.data.modifyFlag) {
            navBack();
            return;
        }
        const { activityInfo } = this.data;
        const { allowAllSpokesman, specificSpokesmanIds } = activityInfo.consignment;
        if (!allowAllSpokesman && (!specificSpokesmanIds || !specificSpokesmanIds.length)) {
            tipToast('请选择代言人');
            return;
        }
        app.event.trigger('getActivityInfo', activityInfo);
        navBack();
    },
})